package cn.tedu.luban.commons.utils;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

public class ByteStreamFromURL {

    /**
     * 获取 URL 的字节流
     * @param urlStr URL地址
     * @return 字节数组
     * @throws IOException 如果读取流失败
     */
    public static byte[] getByteStreamFromURL(String urlStr) throws IOException {
        URL url = new URL(urlStr);
        HttpURLConnection conn = null;
        InputStream is = null;
        ByteArrayOutputStream bos = null;
        try {
            conn = (HttpURLConnection)url.openConnection();
            conn.setRequestMethod("GET");
            conn.setConnectTimeout(5000);
            conn.setReadTimeout(5000);

            if (conn.getResponseCode() == 200) {
                is = conn.getInputStream();
                bos = new ByteArrayOutputStream();

                byte[] buffer = new byte[1024];
                int len;
                while ((len = is.read(buffer)) != -1) {
                    bos.write(buffer, 0, len);
                }

                return bos.toByteArray();
            } else {
                throw new IOException("Could not read URL: " + urlStr);
            }
        } finally {
            if (bos != null) {
                bos.close();
            }
            if (is != null) {
                is.close();
            }
            if (conn != null) {
                conn.disconnect();
            }
        }
    }
}

